package com.gugu.procedure.controller;


import com.gugu.procedure.bean.ProductionRecord;
import com.gugu.procedure.bean.Replenishment;
import com.gugu.procedure.common.Constant;
import com.gugu.procedure.common.MessageResult;
import com.gugu.procedure.dao.ReplenishmentDao;
import com.gugu.procedure.exceptions.BusinessException;
import com.gugu.procedure.param.ReplenishmentCheckParam;
import com.gugu.procedure.service.ProductionRecordService;
import com.gugu.procedure.service.ReplenishmentService;
import com.gugu.procedure.util.BeanUtil;
import com.gugu.procedure.util.DateUtil;
import com.gugu.procedure.util.ExcelUtil;
import com.gugu.procedure.util.StringUtil;
import com.gugu.procedure.vo.ReplenishmentVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = {"补料模块"})
@RequestMapping("replenishment")
public class ReplenishmentController extends BaseController {


    @Autowired
    private ReplenishmentService replenishmentService;

    @Autowired
    private ReplenishmentDao replenishmentDao;
    @Autowired
    private ProductionRecordService productionRecordService;

    @GetMapping("open/listReplenishment")
    @ApiOperation(value = "批量补料信息查询")
    public MessageResult listReplenishment(String orderNo, String number) {
        ProductionRecord productionRecord = productionRecordService.queryByOrderNoAndNumberAndProduction(orderNo, number);
        if (productionRecord == null) {
            return MessageResult.error("找不到当前产品流程记录，请先产看产品流转详情");
        }
        Map <String, Object> map = new HashMap <>();
        List list = replenishmentService.listReplenishment(orderNo, number, productionRecord.getProduction());
        map.put("list", list);
        map.put("specs", productionRecord.getSpecs());
        map.put("production", productionRecord.getProduction());
        return MessageResult.getSuccessInstance(map);
    }

    @PostMapping("check")
    @ApiOperation(value = "审批")
    public MessageResult add(@RequestBody ReplenishmentCheckParam replenishmentCheckParam) {
        if (Constant.REPLENISHMENT_PASS.equals(replenishmentCheckParam.getStatus())) {
            return replenishmentService.checkPass(getRole(), getAccount(), getName(), replenishmentCheckParam.getId(), replenishmentCheckParam.getProduction(), replenishmentCheckParam.getRemark());
        } else
            return replenishmentService.checkRefuse(getAccount(), getName(), replenishmentCheckParam.getId(), replenishmentCheckParam.getRemark());
    }

    @PostMapping("add")
    @ApiOperation(value = "新增补料审批")
    public MessageResult add(@RequestBody Replenishment replenishment) {
        replenishment.setCreateTime(DateUtil.getFormatedDateTime());
        replenishment.setOperator(getAccount());
        replenishment.setOperatorName(getName());
        replenishment.setStatus(Constant.STATUS_0);
        ProductionRecord productionRecord = productionRecordService.queryByOrderNoAndNumberAndProduction(replenishment.getOrderNo(), replenishment.getNumber());
        replenishment.setProduction(productionRecord.getProduction());
        productionRecord.setStatus(Constant.PRODUCTION_RECORD_2);
        productionRecordService.update(productionRecord);
        checkReplenishment(replenishment);
        return replenishmentService.save(replenishment);
    }

    /**
     * 新增补料申请校验  如果某个产品已经提交了补料申请还没审核 就不允许再新增补料申请记录
     * 即根据订单号和摸具编号查询是否有未审批的补料申请记录
     *
     * @param replenishment
     */
    private void checkReplenishment(Replenishment replenishment) {
        // 部门不能为空
        if (StringUtil.isEmpty(replenishment.getDept())) {
            throw new BusinessException("部门不能为空");
        }
        Replenishment bean = replenishmentDao.findTopByOrderNoAndNumberAndStatus(replenishment.getOrderNo(), replenishment.getNumber(), replenishment.getStatus());
        if (bean != null) {
            throw new BusinessException("模具编号" + replenishment.getNumber() + "已存在待审核的补料申请记录，请先进行审批操作");
        }
    }


    @PostMapping("open/addList")
    @ApiOperation(value = "新增补料审批-批量")
    @Transactional
    public MessageResult addList(@RequestBody Replenishment replenishment) {
        String number = replenishment.getNumber();
        List <String> list = StringUtil.stringToList(number, ",");
        for (String num : list) {
            Replenishment bean = new Replenishment();
            BeanUtil.copyProperties(replenishment, bean);
            bean.setCreateTime(DateUtil.getFormatedDateTime());
            bean.setNumber(num);
            bean.setStatus(Constant.STATUS_0);
            checkReplenishment(bean);
            ProductionRecord productionRecord = productionRecordService.queryByOrderNoAndNumberAndProduction(bean.getOrderNo(), bean.getNumber());
            bean.setProduction(productionRecord.getProduction());
            productionRecord.setStatus(Constant.PRODUCTION_RECORD_2);
            productionRecordService.update(productionRecord);
            replenishmentService.save(bean);
        }
        return MessageResult.success();
    }

    @GetMapping("page")
    @ApiOperation(value = "分页查询")
    public MessageResult page(String status, String month, String orderNo, String staffName, int pageNo, int pageSize) {
        String role = getRole();
        if (Constant.MANAGER_WAREHOUSE.equals(role) || Constant.MANAGER_QC.equals(role) || role.contains(Constant.MANAGER_ROLE)
                || Constant.MANAGER_TECHNOLOGY.equals(role)) {
            if (role.contains(Constant.MANAGER_ROLE)) {
                role = null;
            }
            return replenishmentService.page(role, status, orderNo, month, staffName, pageNo, pageSize);
        } else {
            MessageResult mr = MessageResult.success();
            mr.setTotal(0);
            mr.setTotalElement(new ArrayList());
            return mr;
        }


    }


    @GetMapping("open/queryReplenishmentParams")
    @ApiOperation(value = "补料参数查询")
    public MessageResult queryReplenishmentParams(String orderNo, String specs) {
        return MessageResult.getSuccessInstance(replenishmentService.queryReplenishmentParams(orderNo, specs));
    }

    @GetMapping("open/export")
    @ApiOperation(value = "导出")
    public void export(HttpServletResponse response, String status, String orderNo, String month, String staffName) {
        String role = null;
        MessageResult mr = replenishmentService.page(role, status, orderNo, month, staffName, 1, Integer.MAX_VALUE);
        List <ReplenishmentVo> voList = mr.getTotalElement();
        ExcelUtil.download(response, request, voList, ReplenishmentVo.class, "补料申请");
    }


}
